#include <QCheckBox>
#include <QHBoxLayout>
#include "ItemFlag.h"

QWidget *ItemFlag::createWidget(WidgetStyle s)
{
    auto w = new QWidget;
    auto layout = new QHBoxLayout(w);
    for (int i = 0; i < m_enum.keyCount(); i++)
    {
        auto checkBox = new QCheckBox;
        checkBox->setObjectName(m_enum.valueToKey(m_enum.value(i)));
        checkBox->setText(tr(m_enum.valueToKey(m_enum.value(i))));
        layout->addWidget(checkBox);
        connect(checkBox, &QCheckBox::clicked, this, &ItemFlag::onWidgetEditedWrapper);
    }
    return w;
}

void ItemFlag::update(QWidget *widget, UpdateOption option)
{
    if (widget != nullptr)
    {
        if (option == UpdateOption::WidgetContent)
        {
            QObjectList objects = widget->children();
            for (auto obj : objects)
            {
                QCheckBox *checkBox = qobject_cast<QCheckBox*>(obj);
                if (checkBox != nullptr)
                {
                    checkBox->setChecked(false);
                    if (m_data.contains(m_enum.keyToValue(checkBox->objectName().toUtf8().data())))
                    {
                        checkBox->setChecked(true);
                    }
                }
            }
        }
        else if (option == UpdateOption::Item)
        {
            m_data.clear();
            QObjectList objects = widget->children();
            for (auto obj : objects)
            {
                QCheckBox *checkBox = qobject_cast<QCheckBox*>(obj);
                if (checkBox != nullptr && checkBox->isChecked())
                {
                    m_data.insert(m_enum.keyToValue(checkBox->objectName().toUtf8().data()));
                }
            }
        }
    }
    else
    {
        qWarning() << "";
    }
}

void ItemFlag::writeToData(QDataStream &stream) const
{
    stream << m_data;
}

void ItemFlag::readFromData(QDataStream &stream)
{
    stream >> m_data;
    emit itemEdited();
}
